package org.example.algorithm.matrix;

import java.util.HashSet;

public class SetZeroesSolution {

    //空间复杂度O(1)解法
    public void setZeroes(int[][] matrix) {
        if (matrix.length == 0) {
            return;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        boolean rowFlag = false;
        boolean colFlag = false;
        for (int i=0;i<row;i++) {
            if (matrix[i][0] == 0) {
                colFlag = true;
            }
        }
        for (int j=0;j<col;j++) {
            if (matrix[0][j] == 0) {
                rowFlag = true;
            }
        }
        for (int i=1;i<row;i++) {
            for (int j=1;j<col;j++) {
                if (matrix[i][j] == 0) {
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        for (int i=1;i<row;i++) {
            for (int j=1;j<col;j++) {
                if (matrix[0][j] == 0 || matrix[i][0] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        if (rowFlag) {
            for (int j=0;j<col;j++) {
                matrix[0][j] = 0;
            }
        }
        if (colFlag) {
            for (int i=0;i<row;i++) {
                matrix[i][0] = 0;
            }
        }
    }

    public void setZeroes2(int[][] matrix) {
        if (matrix.length == 0) {
            return;
        }
        int row = matrix.length;
        int column = matrix[0].length;
        HashSet<Integer> rowSet = new HashSet<>();
        HashSet<Integer> columnSet = new HashSet<>();
        for (int i=0;i<row;i++) {
            for (int j=0;j<column;j++) {
                if (matrix[i][j] == 0) {
                    rowSet.add(i);
                    columnSet.add(j);
                }
            }
        }
        for (int i=0;i<row;i++) {
            for (int j=0;j<column;j++) {
                if (rowSet.contains(i) || columnSet.contains(j)) {
                    matrix[i][j] = 0;
                }
            }
        }
    }
}
